<?php

namespace App\Models;

use App\Http\Controllers\Resource\YrdController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/*数字资源（元阅读）model*/

class ResourceYrd extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_yrd';

    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /*关联活动类型*/
    public function conType()
    {
        return $this->hasOne(ResourceTypeExternal::class, 'id', 'type_id');
    }


    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        $res = $this->select([
            'id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            'pre_time',
            'img',
            'intro',
            'create_time',
            'big_type_id',
            'type_id',
            'browse_num',
            'is_recom'
        ])->with('conBigType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->with('conType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->where(function ($query) use ($id, $guid) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('guid', $guid);
            }
        })->where('is_del', 1)
            ->first();
        if ($res) {
            $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
            $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取
        }
        return $res;
    }

    /**
     * 添加数据到数据库（更新）
     * @param $data
     */
    public function addData($data)
    {
        if (empty($data['id'])) {
            return false;
        }

        $res = $this->where('data_unique_id', $data['id'])->first(); //获取所有数据，之前下架的现在重新上架
        if (empty($res)) {
            //修改
            $res = new self();
            $guid = get_guid();
            $res->guid = $guid;
        }
        $res->data_unique_id = $data['id'];
        $res->resource_business_id = 9;
        $res->big_type_id = $data['big_type_id'];
        $res->type_id = $data['type_id'];
        $res->book_type = $data['bookType'];
        $res->press = $data['publisher'];
        $res->pre_time = $data['publishDate'];
        $res->img = $data['coverUrl'];
        $res->intro = $data['summary'];
        $res->title = $data['name'];
        $res->author = $data['authors'];
        $res->anchor_name = $data['speaker'] ?? null;
        $res->translator = $data['translator'] ?? null;
        $res->word_count = $data['wordCount'] ?? null;
        $res->size = $data['bookSize'] ?? null;
        $res->tag = $data['bookTags'] ?? null;
        $res->thumbnail = $data['thumbnail'] ?? null;
        $res->time_long = $data['timeLong'] ?? null;
        $res->original_create_time = $data['createdTime'] ?? null;
        $res->first_type = $data['oneCategory'] ?? null;
        $res->second_type = $data['twoCategory'] ?? null;
        $res->categorys = $data['categorys'] ? json_encode($data['categorys'], JSON_UNESCAPED_UNICODE) : null;
        $res->isbn = str_replace('-', '', $data['isbn']);

        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1;
        $res->save();

        //加入到资源总数据库
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->addData($res);

        return $res->id;
    }

    /**
     * 获取数据交集与差集
     * @param $big_type_id 1:电子书   2：有声书
     * @param $data_unique_id_all 所有的数据id
     */
    public function getDataIntersection($big_type_id, $data_unique_id_all)
    {
        $data_unique_id_ed = $this->where('big_type_id', $big_type_id)->where('is_del', 1)->pluck('data_unique_id')->toArray(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($data_unique_id_ed)) {
            return ['add' => $data_unique_id_all, 'del' => []];
        }

        $data_unique_id_all_del = array_diff($data_unique_id_ed, $data_unique_id_all); //对比返回在 $data_unique_id_ed 中但是不在 $data_unique_id_all 的数据删除
        $data_unique_id_all_add = array_diff($data_unique_id_all, $data_unique_id_ed); //对比返回在 $change_id_value 中但是不在 $data_unique_id_ed 的数据添加

        return ['add' => $data_unique_id_all_add, 'del' => $data_unique_id_all_del];
    }


    /**
     *删除下架数据
     * @param $big_type_id 1:电子书   2：有声书
     * @param $data_unique_id_all 所有要删除的数据
     */
    public function deleteData($big_type_id, $data_unique_id_all)
    {
        $data_guid_all = $this->whereIn('data_unique_id', $data_unique_id_all)->where('big_type_id', $big_type_id)->where('is_del', 1)->pluck('guid')->toArray(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($data_guid_all)) {
            return true;
        }
        $this->whereIn('guid', $data_guid_all)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);

        //删除总数据
        foreach ($data_guid_all as $key => $val) {
            $resourceTotalModel = new ResourceTotal();
            $resourceTotalModel->deleteData($val);
        }
        return true;
    }



    /**
     * 获取图书目录
     * @param guid  资源guid
     */
    public function getBookCatalogue($guid)
    {
        $key = md5('getYrdBookCatalogue-' . $guid);
        $res = Cache::get($key);
        if (empty($res)) {
            $book_info = $this->select('data_unique_id', 'big_type_id')->where('guid', $guid)->where('is_del', 1)->first();
            $book_id = trim($book_info['data_unique_id']);
            if (empty($book_id)) {
                return false;
            }
            $yrdObj = new YrdController();
            $res = $yrdObj->getBookCatalogue($book_id);
            if (!empty($res['data'])) Cache::set($key, $res, 10); //缓存10分钟，因为音频地址只有2个小时有效期
        }

        if (empty($res['data'])) {
            return null;
        }
        return $res;
    }

    /**
     * 获取图书资源地址
     * @param user_id  用户id（唯一即可）当前使用用户token
     * @param guid  资源guid
     * @param chapter_id  章节id
     * @param href  toc 目录中的href
     * @param fragment_id  toc 目录中的fragmentId （锚点）
     */
    public function getChapterAddress($user_id, $guid, $chapter_id, $href, $fragment_id)
    {
        $book_info = $this->select('data_unique_id', 'big_type_id')->where('guid', $guid)->where('is_del', 1)->first();
        $book_id = trim($book_info['data_unique_id']);
        if (empty($book_id)) {
            return false;
        }
        $yrdObj = new YrdController();
        $res = $yrdObj->getReadPage($user_id, $book_id, $chapter_id, $href, $fragment_id);

        $data = [];
        if ($res) {
            $data['chapter_id'] = $chapter_id;
            $data['book_id'] = $book_id;
            $data['link'] = $res;
        }
        return $data;
    }
}
